using Assets.Scripts.Common;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Assets.Scripts.Controllers
{
    internal class SoundsController : MonoBehaviour
    {
        public static SoundsController Instance { get; private set; }

        [SerializeField] private AudioSource _soundsSource;
        [SerializeField] private List<SoundClip> _soundClips;

        private Dictionary<SoundId, AudioClip> _sounds;

        public void Play(AudioSource source, SoundId sound, float pitch)
        {
            if (sound == SoundId.None) return;

            if (_sounds.TryGetValue(sound, out var clip))
            {
                source.clip = clip;
                source.pitch = pitch;
                source.loop = false;

                source.Play();
            }
        }

        public void Play(SoundId sound, float pitch = 1f)
        {
            if (sound == SoundId.None) return;

            if (_sounds.TryGetValue(sound, out var clip))
            {
                _soundsSource.pitch = pitch;
                _soundsSource.PlayOneShot(clip);
            }
        }

        private void Awake()
        {
            _sounds = _soundClips.ToDictionary(k => k.Sound, v => v.AudioClip);

            if (Instance != null)
            {
                Destroy(gameObject);
                return;
            }

            Instance = this;
        }

        private void Start()
        {
            transform.parent = null;
            DontDestroyOnLoad(gameObject);
        }

        [System.Serializable]
        class SoundClip
        {
            public SoundId Sound;
            public AudioClip AudioClip;
        }
    }
}